package com.xdfsoft.homeserve.utils;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author chanchaw
 * @create 2025-05-14 9:18
 */
@Service
public class CmdUtils {
    private static final Logger logger = LoggerFactory.getLogger("cmd");
    private static final String OPENWRT_HOST = "192.168.66.1";
    private static final int OPENWRT_PORT = 19834;
    private static final String OPENWRT_USERNAME = "root";
    private static final String OPENWRT_PASSWORD = "!7758ChanChaw@";
    public static void execLinux(String cmdString){
        JSch jsch = new JSch();
        Session session = null;

        try {
            // 创建SSH会话
            session = jsch.getSession(OPENWRT_USERNAME, OPENWRT_HOST, OPENWRT_PORT);
            session.setPassword(OPENWRT_PASSWORD);

            // 设置不检查主机密钥(仅用于测试环境，生产环境应配置正确的密钥)
            session.setConfig("StrictHostKeyChecking", "no");

            // 连接会话
            session.connect();
//            System.out.println("成功连接到OpenWrt设备");
            logger.info("成功连接到OpenWrt设备");

            // 打开通道并执行命令
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmdString);
            logger.info("即将执行的命令：" + cmdString);

            // 获取命令输出
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            // 读取命令输出
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
//                    System.out.print(new String(tmp, 0, i));
                    logger.info(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) continue;
                    //System.out.println("退出状态: " + channel.getExitStatus());
                    logger.info("退出状态: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }

            // 断开连接
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
//            System.err.println("SSH连接错误: " + e.getMessage());
            logger.info("SSH连接错误: " + e.getMessage());
        } catch (IOException e) {
//            System.err.println("IO错误: " + e.getMessage());
            logger.info("IO错误: " + e.getMessage());
        } finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public static void execWin(String cmdString) throws IOException, InterruptedException {
        // 构建命令行
        String utf8cmd = "chcp 65001>nul && " + cmdString;
        String[] cmd = {"cmd.exe", "/c", utf8cmd};

        // 创建进程并执行命令
        ProcessBuilder builder = new ProcessBuilder(cmd);
        logger.info("====== 执行 win 命令 ======");
        logger.info("调用方传入的命令：" + cmdString);
        logger.info("完整命令:" + String.join(",",cmd));
        Process process = builder.start();

        // 读取命令执行的输出信息
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.info(line);
        }

        // 等待命令执行完成
        int exitCode = process.waitFor();
        logger.info("Command executed with exit code: " + exitCode);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
    }
}
